package com.webuy.h5.container

import android.content.Context
import android.graphics.Bitmap
import android.text.TextUtils
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import androidx.core.util.Consumer
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.Utils
import okhttp3.Cache
import okhttp3.OkHttpClient
import timber.log.Timber
import java.io.File

/**
 *  author: luoXiong
 *  e-mail: 382060748@qq.com
 *  date: 2021/7/22 17:21
 *  version: 1.0
 *  desc:
 */
object JlH5Container {
    private var okHttpClient: OkHttpClient? = null
    private var imgEngine: WebViewImageLoadEngine? = null

    fun registerImageLoadEngine(imgEngine: WebViewImageLoadEngine) {
        this.imgEngine = imgEngine
    }
    // img2Bitmap: () -> Bitmap

    fun init(okHttpClient: OkHttpClient,imgEngine: WebViewImageLoadEngine) {
        this.okHttpClient = okHttpClient
        this.imgEngine = imgEngine
    }

    fun interceptRequest(context: Context,request: WebResourceRequest?): WebResourceResponse? {
        val url = request?.getUrl().toString()
        if (TextUtils.isEmpty(url)) {
            return null
        }
        var res: WebResourceResponse? = null
        if (imgEngine != null) {
            res = GlideImgCacheManager.interceptRequest(context,url)
        }
        return res
    }


    fun getImgEngine(): WebViewImageLoadEngine? {
        return imgEngine
    }

    fun getOkHttpClient(): OkHttpClient? {
        return okHttpClient
    }

    fun getOkHttpCacheInterceptor(): MyOkHttpCacheInterceptor {
        return MyOkHttpCacheInterceptor()
    }
    fun getOkhttpCache(): Cache {
        //设置缓存的目录文件
        val httpCacheDirectory = File(Utils.getApp().externalCacheDir, "h5-webview-http-cache")
        //仅作为日志使用
        if (httpCacheDirectory.exists()) {
            val result = FileUtils.listFilesInDir(httpCacheDirectory)
            for (file in result) {
                Timber.d("file = " + file.absolutePath)
            }
        }
        //缓存的大小，OkHttp会使用DiskLruCache缓存
        val cacheSize = 200 * 1024 * 1024 // 200 MiB
        val cache = Cache(httpCacheDirectory, cacheSize.toLong())
        return cache
    }
}